package com.moji.controller;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

public class XmlUploadExample {
    public static void main(String[] args) {
        // 创建Document对象
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();

            // 创建根元素
            Element rootElement0 = doc.createElement("urlset");
            rootElement0.setAttribute("xmlns","http://www.sitemaps.org/schemas/sitemap/0.9");
            doc.appendChild(rootElement0);

            Element rootElement1 = doc.createElement("url");
            rootElement0.appendChild(rootElement1);

            // 创建子元素
            Element child0 = doc.createElement("loc");
            child0.appendChild(doc.createTextNode("http://47.93.153.16/news/detail?id=1409"));
            rootElement1.appendChild(child0);

            // 创建子元素
            Element child1 = doc.createElement("lastmod");
            child1.appendChild(doc.createTextNode("2024-09-05"));
            rootElement1.appendChild(child1);

            // 创建子元素
            Element child2 = doc.createElement("changefreg");
            child2.appendChild(doc.createTextNode("always"));
            rootElement1.appendChild(child2);

            // 创建子元素
            Element child3 = doc.createElement("priority");
            child3.appendChild(doc.createTextNode("1.0"));
            rootElement1.appendChild(child3);

            // 将DOM内容写入文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("output.xml"));

            // 输出内容到指定文件
            transformer.transform(source, result);

            // 将文件上传到指定目录
            File xmlFile = new File("output.xml");
            File targetDir = new File("/resources/");
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File uploadedFile = new File(targetDir, "uploaded1.xml");
            xmlFile.renameTo(uploadedFile);

            System.out.println("XML file uploaded to " + targetDir.getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}